<script setup lang="ts">
import { requiredCheck, validatePortCheck } from "@/utils/verify";
import { ref } from "vue";
import { addData, editData, updateFileByWeb } from "@/api/modules/resource/service";
import BaseUpload from "@/components/BaseUpload/index.vue";

interface Props {
  title?: string;
  rowData?: Object;
  webData?: Object;
}

const props = withDefaults(defineProps<Props>(), {
  title: "新增服务",
  rowData: undefined,
  webData: undefined
});
defineOptions({
  name: "UpdateForm" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ElMessage } from "element-plus";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    name: [...requiredCheck("请输入服务名称")],
    file: [...requiredCheck("请上传服务安装包")],
    port: [...requiredCheck("请输入端口"), { validator: validatePortCheck }]
  },
  defaultData: {
    grade: "高",
    proto: "http",
    type: "1"
  }
});

async function submitCb() {
  await updateFormRef.value.validate();
  let text;
  if (props.webData) {
    text = props.webData;
  } else {
    text = props.rowData.originData[5];
    text = JSON.parse(text);
  }

  console.log(`text:::`, text);

  let priMap = new Map([
    ["低", "1"],
    ["中", "2"],
    ["高", "3"]
  ]);
  if (!props.webData) {
    // 执行编辑
    // 存在执行编辑
    text.app.forEach(item => {
      if (item.id === props.rowData.id) {
        item.file = updateFormData.file.includes("http/") ? updateFormData.file : "http/" + updateFormData.file;
        item.name = updateFormData.name;
        item.pri = priMap.get(updateFormData.grade);
        item.proto = updateFormData.proto;
        item.port = updateFormData.port;
        item.type = Number(updateFormData.type);
        item.uptime = parseInt(updateFormData.uptime / 1000);
      }
    });
  } else {
    if (updateFormData.tempFile) {
      await updateFileByWeb({
        file: updateFormData.tempFile
      });
    }
    let lastData = text.app[text.app.length - 1];
    let obj = {
      name: updateFormData.name,
      type: Number(updateFormData.type),
      port: updateFormData.port,
      proto: updateFormData.proto,
      pri: priMap.get(updateFormData.grade),
      file: updateFormData.file.includes("http/") ? updateFormData.file : "http/" + updateFormData.file,
      uptime: parseInt(updateFormData.uptime / 1000),
      state: 1,
      id: lastData.id + 1
    };
    text.app.push(obj);
  }
  let sendData = {
    id: "5",
    text: text
  };
  await editData(sendData);
  ElMessage.success("操作成功");
  showHandle.value = false;
  emits("success");
}

function createFile() {
  const tempInput = document.createElement("input");

  tempInput.type = "file";

  tempInput.accept = ".jar,.war,.zip,.gz,.tar.gz,.rar";

  tempInput.click();

  tempInput.addEventListener("change", async () => {
    try {
      console.info(tempInput.files[0]);

      updateFormData.file = tempInput.files[0].name;
      updateFormData.tempFile = tempInput.files[0];
    } catch (error) {}
  });
}
</script>

<template>
  <div
    class="update-form mg-r-sm"
    style="display: inline-block"
    @click="
      openHandle({
        row: {
          ...rowData
        },
        id: props.rowData?.id
      })
    "
  >
    <slot>
      <el-button type="primary">新增</el-button>
    </slot>
  </div>
  <base-dialog @confirm="submitCb()" width="560px" :title="title" v-model="showHandle">
    <div class="details">
      <div class="details-main">
        <el-form ref="updateFormRef" :model="updateFormData" :rules="updateFormRules" label-width="120px" label-suffix="：">
          <div class="h-box">
            <el-form-item label="服务名称" prop="name">
              <el-input style="width: 140px" v-model="updateFormData.name" auto-complete="off" placeholder="请输入服务名称" />
            </el-form-item>
            <el-form-item label="编码语言" prop="type">
              <el-select style="width: 140px" v-model="updateFormData.type" auto-complete="off" placeholder="请选择">
                <el-option label="PHP" value="1"></el-option>
                <el-option label="JAVA" value="2"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="h-box" style="max-width: 520px; flex-wrap: wrap">
            <el-form-item label="服务安装包" prop="file">
              <div style="max-width: 140px" @click="createFile">
                <el-input :disabled="!Boolean(webData)" :model-value="updateFormData.file ? updateFormData.file : '点击上传'"
                  >
                </el-input>
              </div>
              <el-input
                style="width: 140px"
                type="hidden"
                v-model="updateFormData.file"
                auto-complete="off"
                placeholder="请上传服务安装包"
              />
            </el-form-item>
            <el-form-item label="网络协议" prop="proto">
              <el-select style="width: 140px" v-model="updateFormData.proto" auto-complete="off" placeholder="请选择">
                <el-option label="http" value="http"></el-option>
                <el-option label="https" value="https"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="h-box">
            <el-form-item label="端口" prop="port">
              <el-input style="width: 140px" v-model="updateFormData.port" auto-complete="off" placeholder="请输入端口" />
            </el-form-item>
            <el-form-item label="危险等级" prop="grade">
              <el-select style="width: 140px" v-model="updateFormData.grade" auto-complete="off" placeholder="请选择">
                <el-option label="高" value="高"></el-option>
                <el-option label="中" value="中"></el-option>
                <el-option label="低" value="低"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <template #footer-more-button></template>
  </base-dialog>
</template>

<style lang="scss" scoped>
.update-form{
  display: inline-flex !important;
  align-items: center;
}
</style>
